<template>
    <!-- 活动管理-新闻模块页面 -->
    <div class="app-container">
    <!-- 搜索工具栏 -->
    <section>
      <so-tool-bar :toolData="toolData" :query="listQuery" @search="search" />
    </section>
     <!-- 其他操作 -->
    <section class="filter-container">
      <el-row>
        <el-col :span="15">
          <el-button class="filter-item" type="primary" size="small" @click="haveTop(1)">置顶</el-button>
          <el-button class="filter-item" type="primary" size="small" @click="haveTop(0)">取消置顶</el-button>
        </el-col>
        <el-col :span="9">
          <section style="float: right">
            <el-button class="filter-item" type="danger" size="small" @click="delRows">批量删除</el-button>
            <el-button class="filter-item" type="primary" size="small" @click="openForm('add')">发布帖子</el-button>
          </section>
        </el-col>
      </el-row>
    </section>
    <!-- 表格 -->
    <el-table :data="tableList" v-loading="loading" element-loading-text="正在查询中。。。" stripe highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column align="center" width="30">
        <template slot-scope="scope">
          <i class="iconfont ali-zhiding" v-show="scope.row.top_status == 1"></i>
        </template>
      </el-table-column>
      <el-table-column align="center" label="学习主题" prop="title">
      </el-table-column>
      <el-table-column align="center" label="发布人" prop="create_user">
      </el-table-column>
      <el-table-column align="center" label="发布时间" prop="create_time">
      </el-table-column>
      <el-table-column align="center" label="列表链接">
        <template slot-scope="scope">
          <el-button v-clipboard:copy="'https://cloud.anyolife.com/StudyHome'" v-clipboard:success="onCopy" v-clipboard:error="onError" 
          type="text">复制链接</el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="详情链接">
        <template slot-scope="scope">
          <el-button
            v-clipboard:copy="'https://cloud.anyolife.com/ActivityDetail' + '?id=' + scope.row.id
            + '&status=' + scope.row.active_status + '&name=' + 'home'"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            type="text"
          >复制链接</el-button>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="操作" width="230px">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="delRow(scope.row)">删除</el-button>
          <el-button type="text" size="mini" @click="editRow('edit',scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <section>
      <so-pagination :query="listQuery" @initList="initList"/>
    </section>
     <!-- 发布新闻 -->
    <section>
      <el-dialog :visible.sync="dialog.isShow" :show-close="false" :fullscreen="fullscreen" :before-close="beforeClose" :close-on-click-modal="false">
        <el-row slot="title">
          <el-col :span="10" style="padding-top: 5px">
            <span style="font-size: 18px;">{{dialog.title}}</span>
          </el-col>
          <el-col :span="2" :offset="11">
            <el-button type="text" v-if="!fullscreen" icon="iconfont ali-quanping" @click="fullscreen = true" style="float: right"></el-button>
            <el-button type="text" v-else icon="iconfont ali-zuixiaohua" @click="fullscreen = false" style="float: right"></el-button>
          </el-col>
          <el-col :span="1">
            <el-button type="text" icon="iconfont ali-guanbi" @click="dialog.isShow = false" style="float: right"></el-button>
          </el-col>
        </el-row>
        <el-form :model="form" ref="createArticle" label-width="90px">
          <el-form-item label="学习主题" prop="title" :rules="filter_rules({required:true})">
            <el-input clearable style="width: 300px;" placeholder="请输入主题" v-model.trim="form.title">
            </el-input>
          </el-form-item>
          <el-form-item label="活动封面" prop="banner_path" :rules="filter_rules({type: 'upload'})">
            <img v-if="form.banner_path" :src="form.banner_path" class="avatar" @click="sizeSet">
            <i v-else class="el-icon-plus avatar-uploader-icon" @click="sizeSet"></i>
          </el-form-item>
          
            <el-form-item prop="study_content" label="学习内容" >
              <UE @showUpload="showUpload" :defaultMsg.sync='defaultMsg' ref="ue"></UE>
            </el-form-item>

            <el-form-item label="文件上传" prop="file_url">
              <el-upload class="upload-demo" action="/api/backstage/fileUpload" multiple :limit="3" name="file_path"
                :file-list="fileList" 
                :on-remove="handleRemove" 
                :before-remove="beforeRemove"
                :on-success='handleSuccess'
                :on-exceed="handleExceed"
                accept=".xls,.xlsx,.doc,.docx,.csv,.txt,.pdf,.ppt,.pptx"
                >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">*只能上传文件,最多上传3个</div>
              </el-upload>
            </el-form-item>

            <el-form-item label="上传视频" prop="video_url">
              <el-upload class="upload-demo" action="/api/backstage/fileUpload" :limit="1" name="file_path"
                :file-list="videoList" :on-remove="handleRemove2" :before-remove="beforeRemove2"
                :on-success='handleSuccess2' :before-upload="beforeUpload2" :on-exceed="handleExceed2"
                accept=".mp4">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">*只能上传视频，只能上传1个</div>
              </el-upload>
            </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialog.isShow = false">取 消</el-button>
          <el-button type="primary"  @click.native="validate('createArticle')">提 交</el-button>
        </span>
      </el-dialog>
    </section>
     <!-- 上传图片 组件 -->
    <section>
      <size-temp ref="size" :img.sync="form.banner_path" title="图片设置"></size-temp>
    </section>
    <section>
      <UeUpload ref="vupload" @addUeditorImg="addUeditorImg" img="卐" title="添加图片"></UeUpload>
    </section>
    </div>
</template>

<script>
import { searchTool} from '@/utils'
import SoPagination from '@/components/SoPagination'     //分页
import SoToolBar from '@/components/SoToolBar'          //搜索工具
import { status_opt, audit_status, toolData } from './community'
import sizeTemp from '@/components/draggableSize'      //上传图片控件
import {news_list, news_listAll, news_save, news_edit, news_delete, news_deleteAll, news_findById, updateTopStatus} from '@/api/newsModule'   //接口
import { create } from 'domain';
import UE from '@/components/Ueditor';
import UeUpload from '@/components/UeUpload'

export default {
    name: "newsModule",
    components: { SoToolBar, SoPagination, sizeTemp, UE ,UeUpload },
    data(){
      return{
        ossPublicUrl: localStorage.getItem("ossPublicUrl"),
        fileList: [],
        videoList: [],
        form: { content_type: 0, banner_path: '', file_url: '', video_url: '' },
        fullscreen: false,
        dialog: { isShow: false },
        //表格数据
        tableList:[],
        loading: false,
        toolData: toolData, //搜索工具栏初始化
        multipleSelection: [],
        defaultMsg: '',
        listQuery: { start: 0, limit: 10, total: 0, current: 1 ,content_type :0},
        options:[ {id: 1, name: '链接'}, {id: 0, name: '自定义'}]
      }
    },
    methods:{
      videoUpload(file) { 				
				var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)				
				const extension = testmsg === 'AVI'
				const extension2 = testmsg === 'mp4'
				const extension3 = testmsg === 'rmvb'
				const isLt2M = file.size / 1024 / 1024 < 50     //这里做文件大小限制
				if(!extension && !extension2) {
           this.$message.warning("上传视频只能是 MP4、AVI、rmvb格式");
				}
				if(!isLt2M) {
					this.$message.warning('上传视频大小不能超过 50MB!');
				}
				return extension || extension2 || extension3 && isLt2M
      },

      beforeUpload(file) { 				
				var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)				
				const extension = testmsg === 'pdf'
				const extension2 = testmsg === 'docx'
				const isLt2M = file.size / 1024 / 1024 < 5     //这里做文件大小限制
				if(!extension && !extension2) {
           this.$message.warning("上传文件只能是 pdf、docx格式");
				}
				if(!isLt2M) {
					this.$message.warning('上传文件大小不能超过 5MB!');
				}
				return extension || extension2 && isLt2M
      },
      
      handleSuccess(res,file,fileList){
        if(res.status == 100){
            this.form.file_url = JSON.stringify(fileList);
            this.$message.success('上传文件成功!')
        }
      },
      handleRemove(file, fileList) {
        this.form.file_url = JSON.stringify(fileList);
        this.$message.success("文件删除成功！");
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        // return this.$confirm(`确定移除 ${ file.name }？`);
      },

      handleSuccess2(res,file,fileList){
        if(res.status == 100){
            this.form.video_url = JSON.stringify(fileList);
            this.$message.success('上传文件成功!')
        }
      },
      handleRemove2(file, fileList) {
        this.form.video_url = JSON.stringify(fileList)
        this.$message.success("文件删除成功！");
      },
      handleExceed2(files, fileList) {
        this.$message.warning(`视频上传文件只能上传 1 个文件`);
      },
      beforeRemove2(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      beforeUpload2(file){
        let testVideo=file.name.substring(file.name.lastIndexOf('.')+1)
        let videoType = testVideo == 'mp4'
        if (!videoType) {
          this.$message({  
              message: '上传视频只能是 mp4 格式!',  
              type: 'warning'  
          });  
        }
        return videoType;
      },
      onCopy: function() {
        this.$message({
          type: "success",
          message: "复制成功"
        });
      },
      onError: function() {
        this.$message.error("复制失败");
      },
      //置顶
      async haveTop(e) {//1 置顶 0 取消
        if (this.multipleSelection.length == 0) {
          this.$message.warning('请先选择需要调整单元');
          return;
        }
        const ids = this.multipleSelection.map(item => item.id).join();
        this.loading = true;
        let { data } = await updateTopStatus({ ids: ids, top_status: e });
        this.loading = false;
        if (data.status === 100) {
          await this.initList();
          this.$message.success('操作成功');
        }
      },
      addUeditorImg(val){
        this.$refs.ue.addToContent(`<img src="${val}">`)
      },
      sizeSet(){
        this.$refs.size.open()
      },
      beforeClose(){
      // this.$refs.ue.clear();
        this.dialog.isShow=false;
      },
      async delRow(data) {  //删除
        let Id = data.id
        try {
          let res = await this.$confirm("确认删除吗？");
          if (res == "confirm") {
            this.loading = true;
            let { data } = await news_delete({ id: Id });
            if (data.status == 100) {
              this.$message.success("删除成功");
            }
            this.initList();
            this.loading = false;
          }
        } catch (error) {
          console.log(error, "error");
          this.$message.warning('删除取消');
        }
      },
      showUpload(){
        this.$refs.vupload.open()
      },
    // 查询数据
    async initList(){
      this.loading = true;
      const query = {...this.listQuery, company_id:localStorage.getItem("companyId") - 0};
      let {data} = await news_list(query);
      this.loading = false;
      if(data.status === 100){
        this.tableList = data.data.rows;
        this.listQuery.total = data.data.results;
      }
    },
    async openForm() {//打开发布新闻dialog
      this.fromStatus = 'add'
      this.fileList = [], //清空上传文件列表
      this.videoList = [], //清空上传视频列表      
      this.defaultMsg = ''//清空富文本
      this.form = { banner_path: '' } //清空
      this.dialog = { isShow: true, title: '发布学习' }
      this.$nextTick(_ => {
          this.$refs.ue.setContent('<br/>'); //清空富文本
      });
    },

    async editRow(e, row) {//编辑
      this.fromStatus = 'edit';
      let { data } = await news_findById({ id: row.id });
      if (data.status === 100) {
        this.form = data.data
        this.dialog = { isShow: true, title: '编辑学习' }
        this.defaultMsg = data.data.study_content;
        if (data.data.file_url) {
          this.fileList = JSON.parse(data.data.file_url);
        }
        if (data.data.video_url) {
          this.videoList = JSON.parse(data.data.video_url); 
        }
        this.$nextTick(_ => {
          this.$refs.ue.setContent(data.data.study_content);
        });
      }
    },
    // 搜索
    search() {
      let keyWords = { key: 'searchDate', names: ['news_start_time', 'news_end_time'] }
      this.listQuery = searchTool(this.listQuery, keyWords);
      this.initList();
    },
    //批量删除
    async delRows() {//批量删除
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择需要调整单元");
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      try {
        const res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.loading = true;
          const { data } = await news_deleteAll({ array: ids });
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
        }
      } catch (error) {
        console.log(error, "error");
      }
    },

    handleSelectionChange(e) {
      this.multipleSelection = e;
    },
    async saveObj() {
      const params = { ...this.form, company_id: localStorage.getItem("companyId") - 0};
      this.loading = true;
      let { data } = this.fromStatus == 'add' ? await news_save(params) : await news_edit(params);
      this.loading = false;
      if (data.status == 100) {
        this.$message.success(this.fromStatus == 'add' ? '提交成功' : '编辑成功')
        this.initList();
        }
    },
    // 保存
    validate(e) {
      this.form.study_content = this.$refs.ue.getContent(); //富文本内容
      this.form.content_type = 0
      console.log(this.form)
      // return;
      this.$refs[e].validate(valid => {
        if (valid) {
          this.saveObj();
          this.dialog.isShow = false
        } else {
          return false;
        }
      })
    },

    },

    created(){
      this.initList();
    },
}
</script>
<style lang="scss" scoped>
$border: 1px dashed #d9d9d9;
$picture-size: 120px;
$color: #606266;
span {
  font-size: 13px;
  color: $color;
}
.ali-zhiding{
  color: #009900;
  font-size: 20px;
}
.avatar-uploader {
  .el-upload {
    border: $border;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}
.avatar-uploader-icon {
  border: $border;
  font-size: 28px;
  color: #8c939d;
  width: $picture-size;
  height: $picture-size;
  line-height: $picture-size;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
}
.avatar {
  width: 60%;
  display: block;
  border-radius: 5px;
  cursor: pointer;
}
.el-upload__tip {
  color: #F56C6C;
}
</style>
